package com.apexsoft.aas.service.grpc;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.JSONLexer;
import com.alibaba.fastjson.parser.JSONToken;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

public class UInt64Value implements GrpcType, ObjectDeserializer, ObjectSerializer {
    private static final String type = "type.googleapis.com/google.protobuf.UInt64Value";
    public static final UInt64Value instance = new UInt64Value();

    @Override
    public String type() {
        return type;
    }

    @Override
    public Long deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
        final JSONLexer lexer = parser.lexer;
        lexer.nextToken(JSONToken.COLON);
        StringBuilder sb = new StringBuilder();
        char c;
        while ((c = lexer.next()) != '}') {
            sb.append(c);
        }
        lexer.nextToken(JSONToken.LBRACE);
        return Long.valueOf(sb.toString());
    }

    @Override
    public int getFastMatchToken() {
        return JSONToken.LITERAL_INT;
    }

    @Override
    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
        SerializeWriter out = serializer.out;
        JSONObject data = new JSONObject();
        data.put("@type", type());
        data.put("value", object);
        out.write(data.toJSONString());
    }
}
